<template>
  <div class="profile-page">
    <div class="card">
      <h2 class="card-title">个人中心</h2>
      <div class="content">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <el-avatar :size="96" :src="avatarPreview || user.avatar_url" shape="circle">
              <template #default>
                <i class="el-icon-user"></i>
              </template>
            </el-avatar>
          </div>
          <div class="avatar-actions">
          <el-upload
            class="avatar-uploader"
              :before-upload="beforeAvatarUpload"
            :show-file-list="false"
              :http-request="customAvatarUpload"
              accept="image/png,image/jpeg"
          >
              <el-button type="primary" :loading="uploading">上传头像</el-button>
          </el-upload>
            <div class="hint">仅支持 jpg/png，大小不超过 2MB</div>
          </div>
        </div>
        
        <el-form :model="form" label-width="90px" class="form" :disabled="loading">
          <el-form-item label="用户名">
            <el-input v-model="form.username" readonly />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email" readonly />
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input
              v-model="form.bio"
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="介绍一下自己..."
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
            <el-button @click="resetBio" :disabled="saving">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <el-skeleton v-if="initialLoading" :rows="6" animated />
  <el-backtop :right="24" :bottom="24" />
  <div class="back-btn">
    <back-button></back-button>
  </div>
</template>

<script setup>
defineOptions({ name: 'UserProfilePage' })
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import apiInstance, { auth } from '@/api'
import BackButton from '@/components/BackButton.vue'
import '@/assets/common.css'

// 本页数据
const user = ref({ id: null, username: '', email: '', avatar_url: '', bio: '' })
const form = ref({ username: '', email: '', bio: '' })
const loading = ref(false)
const saving = ref(false)
const uploading = ref(false)
const initialLoading = ref(true)
const avatarPreview = ref('')

const backendOrigin = (() => {
  try {
    const raw = apiInstance?.defaults?.baseURL || ''
    const url = new URL(raw)
    return `${url.protocol}//${url.hostname}${url.port ? ':' + url.port : ''}`
  } catch {
    return ''
  }
})()

const normalizeStaticUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) return url
  if (url.startsWith('/static')) {
    return `${backendOrigin}${url}`
  }
  return url
}

/**
 * 拉取用户信息，保持与后端同步
 */
const fetchProfile = async () => {
  loading.value = true
  try {
    const res = await auth.getProfile()
    const info = res?.data?.user || {}
    user.value = {
      id: info.id,
      username: info.username,
      email: info.email,
      avatar_url: normalizeStaticUrl(info.avatar_url || ''),
      bio: info.bio || ''
    }
    form.value.username = user.value.username
    form.value.email = user.value.email
    form.value.bio = user.value.bio
    // 同步本地缓存，便于导航展示
    const cached = JSON.parse(localStorage.getItem('user') || '{}')
    localStorage.setItem('user', JSON.stringify({ ...cached, ...user.value }))
  } catch (e) {
    // 401 将由拦截器处理
  } finally {
    loading.value = false
    initialLoading.value = false
  }
}

/**
 * 头像上传前校验：类型与大小
 * @param {File} file 待上传文件
 * @returns {boolean} 是否通过
 */
const beforeAvatarUpload = (file) => {
  const isAllowedType = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isAllowedType) {
    ElMessage.error('仅支持 JPG/PNG 格式')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  // 预览
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
  return true
}

/**
 * 自定义上传：调用后端头像上传接口（若后端未实现则反馈提示）
 * @param {Object} options element-plus http-request 形参
 */
const customAvatarUpload = async (options) => {
  const { file, onSuccess, onError } = options
  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('avatar', file)
    if (auth.uploadAvatar) {
      const resp = await auth.uploadAvatar(formData)
      const newUrl = normalizeStaticUrl(resp?.data?.avatar_url || '')
      if (newUrl) {
        avatarPreview.value = newUrl
        const cached = JSON.parse(localStorage.getItem('user') || '{}')
        localStorage.setItem('user', JSON.stringify({ ...cached, avatar_url: newUrl }))
      }
    } else {
      await auth.updateProfile(formData)
    }
    ElMessage.success('头像已上传')
    await fetchProfile()
    onSuccess && onSuccess({}, file)
  } catch (e) {
    ElMessage.error('头像上传失败，后端暂未提供该能力')
    onError && onError(e)
  } finally {
    uploading.value = false
  }
}

/**
 * 保存个人简介
 */
const handleSave = async () => {
  saving.value = true
  try {
    await auth.updateProfile({ bio: form.value.bio })
    ElMessage.success('已保存')
    user.value.bio = form.value.bio
    const cached = JSON.parse(localStorage.getItem('user') || '{}')
    localStorage.setItem('user', JSON.stringify({ ...cached, bio: form.value.bio }))
  } catch (e) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const resetBio = () => {
  form.value.bio = user.value.bio || ''
}

onMounted(fetchProfile)
</script>

<style scoped>
.profile-page {
  display: flex;
  justify-content: center;
}
.card {
  width: 100%;
  max-width: 900px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 20px;
}
.card-title {
  font-size: 20px;
  margin-bottom: 16px;
  color: #303133;
}
.content {
  display: grid;
  grid-template-columns: 260px 1fr;
  grid-gap: 24px;
}
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-wrapper {
  margin-bottom: 12px;
}
.avatar-actions .hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
.form {
  width: 100%;
}
@media (max-width: 768px) {
  .content {
    grid-template-columns: 1fr;
  }
}
</style>